#include <iostream>
#include <thread>
#include <atomic>
#include <cmath>
#include <chrono> 
#include <cstdlib>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <bits/stdc++.h>





std::condition_variable cv;
bool IsBufferOccupy = false;
int cnt = 0;
void func(std::mutex* l_mutex,std::condition_variable* cv)
{
    //这里为了解决对同一个缓冲区的同时写入出现错误，特意上锁，因为为了解决同步。
    while(1)
    {
        std::unique_lock<std::mutex> mux(*l_mutex);
        while(!IsBufferOccupy)
        {
            cv->wait(mux);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"Thread ID:" <<std::this_thread::get_id()<<"  "<<"我是线程A "<<cnt++<<"\n";
        IsBufferOccupy = false;
        cv->notify_one();
    }
    
}
void func1(std::mutex* l_mutex,std::condition_variable *cv)
{
    //这里为了解决对同一个缓冲区的同时写入出现错误，特意上锁，因为为了解决同步。
    while(1)
    {
        std::unique_lock<std::mutex> mux(*l_mutex);
        while(IsBufferOccupy)
        {
            cv->wait(mux);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"Thread ID:"  <<std::this_thread::get_id()<<"  "<<"我是线程B "<<cnt++<<"\n";
        IsBufferOccupy = true;
        cv->notify_one();
    }
}

int main()
{
    std::mutex l_mutex;
    std::condition_variable cv;
    std::thread t1(func,&l_mutex,&cv);
    std::thread t2(func1,&l_mutex,&cv);
    
    //让其是真的时候，使得t1,可以占有
    //假的的时候t2可以占有
    IsBufferOccupy = true;
    cv.notify_all();
    if(t1.joinable())
        t1.join();
    if(t2.joinable())
        t2.join();
    return 0;
}